﻿using Dao;
using Infrastructure.Model;
using Infrastructure.MyException;
using ShareCode.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bll
{
    public class BaseTreeBll<T> : BaseContainTitleBll<T> where T : BaseTreeEntity, new()
    {
        protected override BaseTreeDao<T>? Dao => (BaseTreeDao<T>?)base.Dao;

        public async override Task<bool> UpdateStateAsync(List<long> id, int state)
        {
            return await Dao!.UpdateStateAsync(id, state);

        }

        public async virtual Task<T?> GetTreeRootAsync(long id) { return await Dao!.GetTreeRootAsync(id); }

        public async virtual Task<List<long>> GetTreeParentIds(long id) { return await Dao!.GetTreeParentIds(id); }

        protected void Validate(T entity)
        {
            var ex = new ShowUserLogicException("信息验证不通过");

            //if (entity.TheCode.Length < 3) 
            //{
            //    ex.AddSonMessage(nameof(entity.TheCode), "此项长度不足");
            //}
            if ((entity.Title??"").Length < 3)
            {
                ex.AddSonMessage(nameof(entity.Title), "此项长度不足");
            }
            if (ex.SonErrs.Count > 0)
            {
                throw ex;
            }

            if ((entity.TheCode??"").Length > 3)//有时这玩意不需要验证
            {
                var li = this.Dao!.GetList(t => (t.TheCode == entity.TheCode || t.Title == entity.Title) && t.Id != entity.Id);

                foreach (var item in li)
                {
                    if (item.TheCode == entity.TheCode) { ex.AddSonMessage(nameof(entity.TheCode), "系统内已存在"); }
                    if (item.Title == entity.Title) { ex.AddSonMessage(nameof(entity.Title), "系统内已存在"); }
                }
            }
            else
            {
                var li = this.Dao!.GetList(t => t.Title == entity.Title && t.Id != entity.Id);

                foreach (var item in li)
                {
                    if (item.TheCode == entity.TheCode) { ex.AddSonMessage(nameof(entity.TheCode), "系统内已存在"); }
                    if (item.Title == entity.Title) { ex.AddSonMessage(nameof(entity.Title), "系统内已存在"); }
                }
            }

            if (ex.SonErrs.Count > 0)
            {
                throw ex;
            }
        }

        public async virtual Task<bool> TreeInsertSon(T entity)
        {
            Validate(entity);
            return await Dao!.TreeInsertSon(entity);
        }
        public async virtual Task<bool> TreeInsertBefore(T entity, long brotherId)
        {
            Validate(entity);
            return await Dao!.TreeInsertBefore(entity, brotherId);
        }
        public async virtual Task<bool> TreeInsertAfter(T entity, long brotherId)
        {
            Validate(entity);
            return await Dao!.TreeInsertAfter(entity, brotherId);
        }
    }
}
